<!-- 约课的场次信息 -->
<template>
  <div class="c-bg-sgray">
    <div class="c-bg-white c-ph12 c-pt20 c-pb4" v-if="historyList.length > 0">
      <div @click="showHistoryDialog = true" class="c-bg-white c-br20 c-ww110 c-hh40 history-box c-fs22 c-fc-sblack c-flex-row c-flex-center">预约记录</div>
    </div>
    <!-- 可弹框查看所有场次 -->
    <!-- 城市 -->
    <div v-if="sessionDisplayType == 1 && cityArr.length > 0" class="c-p c-w100 c-flex-row c-bg-white c-justify-sb c-aligni-center">
      <div class="c-contextX-scroll c-ws-n c-bg-white c-mr50" id="cityScroll">
        <div class="">
          <div v-for="(item, index) in cityArr" :key="index" :id="'city'+item.rsId" class="c-inlineblack c-textAlign-c c-pr40 c-fs24 c-fc-xblack" :class="index == 0 ? ' c-pl24' : ''" @click="changeCity(item.rsId, index)">
            <span class="c-inlineblack c-ph5 c-pv20" :class="selectRsId == item.rsId ? 'theme-fc' : ''">
              {{item.city}}
            </span>
          </div>
        </div>
      </div>
      <span class="iconfont c-pl14 c-pr24 c-fs30 c-fc-sblack section-icon" @click="showMoreInfo = true">&#xe8a3;</span>
    </div>
    <!-- 专场名称 -->
    <div v-if="sessionDisplayType == 2 && cityArr.length > 0" class="c-p c-w100 c-flex-row c-justify-sb c-bg-white c-aligni-center">
      <div class="c-contextX-scroll c-ws-n c-bg-white c-w90" id="cityScroll">
        <div class="">
          <div v-for="(item, index) in cityArr" :key="index" :id="'city'+item.rsId" class="c-inlineblack c-textAlign-c c-pr40 c-fs24 c-fc-xblack" :class="index == 0 ? ' c-pl20' : ''" @click="changeCity(item.rsId, index)">
            <span class="c-inlineblack c-ph5 c-pv20" :class="selectRsId == item.rsId ? 'theme-fc' : ''">
              {{item.sessionName}}
            </span>
          </div>
        </div>
      </div>
      <span class="iconfont c-inlineblack c-w10 c-textAlign-c c-fs30 c-fc-sblack section-icon" @click="showMoreInfo = true">&#xe89c;</span>
    </div>
    <!-- 场次的内容 期数 -->
    <div class="">
      <div class="c-bg-white c-mt10 c-ph24 c-flex-row c-pv20" v-if="cityArr.length > 0">
        <div class="c-ww240 c-maxh160 c-text-hidden">
          <img class="c-w100" :src="$addXossFilter(dataInfo.poster, require('@/assets/defult270.png'))" alt="">
        </div>
        <div class="c-pl20 c-flex-column c-justify-sb c-w0 c-flex-grow1">
          <div class="c-fs24 c-fc-xblack c-text-ellipsis1">{{dataInfo.sessionName}}</div>
          <div class="c-fs20 c-fc-sblack c-flex-row c-justify-sb c-aligni-center">
            <div>{{dataInfo.isShowEnroll == 1 ? dataInfo.enrollCount + '次预约' : '' }}</div>
            <div @click="goToSectionDetail">查看详情 <span class="iconfont c-fs14 c-fc-gray">&#xe85a;</span></div>
          </div>

        </div>
      </div>
      <!-- 期数组件 -->
      <section-periods
        v-if="cityArr.length > 0"
        ref="periods"
        :periodsList="periodsList"
        from="sectionInfo"
        :rtId="rtId"
        :rpId="rpId"
        :reId="reId"
        :myCalendarList="myCalendarList"
        :coachList="coachList"
        :selectIndex="selectIndex"
        :selectTime="selectTime"
        :coachObject="coachObject"
        :selectTimeIndex="selectTimeIndex"
        :selectCoachIndex="selectCoachIndex"
        :dataInfo="dataInfo"
        :weeked="weeked"
        :selectCityIndex="selectCityIndex"
        :localDate="localDate"
        @itemClick="itemClick"
        @handleClickSelectCalendar="handleClickSelectCalendar"
        @handleClickSelectTime="handleClickSelectTime"
        @handleClickCoachSelect="handleClickCoachSelect">
      </section-periods>
      <loading-status-tem
        v-if="cityArr.length == 0"
        :noData="cityArr.length == 0"
        :noDataText="'暂无专场数据'"
      ></loading-status-tem>
    </div>
    <!-- 点击图标查看跟多的城市信息 -->
    <cj-popup v-model="showMoreInfo" position="bottom">
      <div class="c-bg-white c-ph48 c-maxh600 c-contexty-auto">
        <div v-for="(item, index) in cityArr" :key="index" class="c-fs24 c-fc-222 c-pv30 " :class="index < cityArr.length-1 ? 'c-bd-b1-mgray' : ''" @click="changeCity(item.rsId, index)">{{sessionDisplayType == 1 ? item.city : item.sessionName}}</div>
      </div>
    </cj-popup>
    <!-- 约课预约记录 -->
    <cj-popup v-model="showHistoryDialog" round :closeable="true" close-icon-position="top-right" close-icon="icon-guanbi" @closed="showHistoryDialog=false">
      <section class="c-pv20 c-fs20 c-ph40 c-textAlign-l c-contexty-auto c-maxh760 c-ww600">
        <div class="c-pv20" v-for="(item,index) in historyList" :key="index">
          <p class="c-flex-row c-aligni-center">
            <span class="c-ww48">{{index * 1 + 1}}.</span>
            <span class="c-text-ellipsis1">【{{item.sessionName}}】</span>
          </p>
          <p class="c-pt10 c-fc-sblack c-text-ellipsis1" v-if="item.reservationMode == 2">时间：{{item.startAt}}至{{item.endAt}}</p>
          <p class="c-pt10 c-fc-sblack c-text-ellipsis1" v-if="item.reservationMode == 1">预约时间：{{item.enrollTime}}</p>
          <p class="c-pt10 c-fc-sblack c-text-ellipsis1">地点：{{item.place}}</p>
        </div>
        <div @click="goToMyReservationList" class="c-fs20 theme-fc c-pv20 c-textAlign-c">查看详情</div>
      </section>
    </cj-popup>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js"
import SectionPeriods from '@/components/templates/sectionPeriods.vue'
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
let isLoadingHistory = false;
let weekMap = {
  7: "周日",
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六"
};
export default {
  name: 'SessionInfo',
  components: { SectionPeriods, loadingStatusTem },
  data() {
    return {
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      cityArr: [],
      dataInfo: {}, // 场次的信息
      periodsList: [],
      selectRsId: 1, // 选择的专场id
      rtId: null, // 约课主题的id
      rsId: null,
      reId: null, // 改签的id
      rpId: null, // 预约的场期id 改签过来的时候用到
      timer: null,
      showMoreInfo: false, // 查看更多弹框
      showHistoryDialog: false, // 查看更多弹框
      showMoreHistory: false,
      historyList: [], //预约记录
      sessionDisplayType: 1, // 按什么展示 1地址 2专场名称
      myCalendarList: [],
      selectIndex: 0,
      selectTimeIndex: 0,
      selectTime: '',
      weeked: '',
      localDate: '', // 今天日期
      coachList: [],
      selectCoachIndex: 0,
      coachObject: null,
      selectCityIndex: 0,
    }
  },
  methods: {
    itemClick(obj) {
      this.getEnrollDateList(this.rtId, this.selectRsId, obj.date).then(res => {
        if (this.selectTime != '') {
          this.getCoachList(this.rtId, this.selectRsId, obj.date, this.selectTime);
        } else {
          this.coachList = [];
        }
      })
    },
    handleClickCoachSelect(item, index) {
      if (this.selectCoachIndex == index) {
        this.selectCoachIndex = -1;
        this.coachObject = null;
      } else {
        this.selectCoachIndex = index;
        this.coachObject = item;
      }
    },
    handleClickSelectTime(item, index) {
      this.selectTimeIndex = index;
      this.selectTime = item;
      if (this.selectTime != '') {
        this.getCoachList(this.rtId, this.selectRsId, this.localDate, item);
      } else {
        this.coachList = [];
      }
    },
    handleClickSelectCalendar(item, index) {
      // this.coachList = [];
      this.getEnrollDateList(this.rtId, this.selectRsId, item.date).then(res => {
        if (this.selectTime != '') {
          this.getCoachList(this.rtId, this.selectRsId, item.date, this.selectTime);
        } else {
          this.coachList = [];
        }
      })
    },
    // 获取门店预约模式时间
    getEnrollDateList(rtId, rsId, date) {
      return new Promise((resolve, reject) => {
        utilJs.getMethod(global.apiurl + `reservations/getEnrollDateList?rtId=${rtId}&rsId=${rsId}&date=${date}`, res => {
          let dateArr = [];
          let nowDateStr = utilJs.dateFormat(+new Date());
          let curDate = new Date(nowDateStr.replace(/-/g, "/"));
          let nowWeek = curDate.getDay();
          this.localDate = date;
          this.weeked = weekMap[nowWeek];
          if (res.length > 0) {
            res.forEach((item, index) => {
              let itemDay = new Date(item.date).getDate();
              itemDay = itemDay < 10 ? `0${itemDay}` : itemDay;
              // 选中的日期
              if (date == item.date) {
                this.selectIndex = index;
                this.selectTimeIndex = 0
                if (item.enrollTimes.length > 0) {
                  item.enrollTimes.forEach((item, index) => {
                    if (index == this.selectTimeIndex) {
                      this.selectTime = item;
                      return;
                    }
                  })
                } else {
                  this.selectTime = '';
                }
                this.$refs.periods.handleScroll(index);
              }
              if (item.date == nowDateStr) {
                itemDay = '今';
              }
              let dateItem = {
                week: weekMap[item.week],
                date: item.date,
                enrollTimes: Object.values(item.enrollTimes),
                day: itemDay
              }
              dateArr.push(dateItem)
            });
          }
          this.myCalendarList = dateArr;
          resolve()
        }, () => {
          reject();
        })
      })
    },
    // 获取门店教练
    getCoachList(rtId, rsId, date, time) {
      utilJs.getMethod(global.apiurl + `reservations/getCoachList?rtId=${rtId}&rsId=${rsId}&date=${date}&time=${time}`, res => {
        this.coachList = res;
        if (res.length > 0) {
          res.forEach((item, index) => {
            if (index == this.selectCoachIndex) {
              this.coachObject = item;
            }
          })
        }
      })
    },
    changeCity(rsId, index) { // 切换城市
      this.showMoreInfo = false
      this.selectRsId = rsId;
      this.selectCityIndex = index;
      var el = this.$el.querySelector('#city' + rsId);
      var cityScroll = this.$el.querySelector('#cityScroll');
      if (!el || !cityScroll) { return; }
      // 滑动效果
      let i = cityScroll.scrollLeft;
      var _this = this;
      clearInterval(_this.timer);
      if (i > el.offsetLeft) {
        this.timer = setInterval(function () {
          let left = i < el.offsetLeft + 100 ? el.offsetLeft : el.offsetLeft + 100;
          if (i < left) {
            clearInterval(_this.timer);
            return
          }
          i -= 20;
          cityScroll.scrollLeft = i;
        }, 10);
      } else {
        this.timer = setInterval(function () {
          let left = el.offsetLeft <= 0 ? 0 : el.offsetLeft - 100;
          if (i >= left) {
            clearInterval(_this.timer);
            return
          }
          i += 20;
          cityScroll.scrollLeft = i;
        }, 10);
      }

      this.getPasesList();
    },
    goToMyReservationList() {
      this.$routerGo(this, "push", { path: `/member/myReservation/myReservationList?rtId=${this.rtId}` });
    },
    // 获取预约记录
    getMyReservationList() {
      if (this.companyAuth.enableDeclareModule == 1) {
        return;
      }
      if (isLoadingHistory) {
        return;
      }
      isLoadingHistory = true;
      utilJs.getMethod(global.apiurl + 'reservations/getEnrollByUser?page=1&limit=5&listType=2&rtId=' + this.rtId, (res) => {
        isLoadingHistory = false;
        this.historyList = res.data.data;
        this.showMoreHistory = res.data.total * 1 > 10;
      }, failRes => {
        isLoadingHistory = false;
      });
    },
    getSectionCityList() { // 获取场次信息列表
      let $this = this;
      utilJs.getMethod(global.apiurl + "reservations/getSessionsList?rtId=" + this.rtId,
        function (res) {
          $this.cityArr = res.list;
          if (res.list.length > 0) {
            $this.sessionDisplayType = res.sessionDisplayType;
            $this.selectRsId = $this.cityArr[0].rsId;
            $this.getPasesList();
            $this.getMyReservationList();
          }
        }
      );
    },
    getPasesList() { // 获取场期列表
      let $this = this;
      this.$loading.show();
      utilJs.getMethod(global.apiurl + "reservations/getPhasesList?rtId=" + this.rtId + '&rsId=' + this.selectRsId,
        function (res) {
          $this.$loading.hide();
          $this.dataInfo = res;
          $this.periodsList = res.phases;
          // 门店预约模式请求预约时间
          if (res.reservationMode == 1) {
            let nowDateStr = utilJs.dateFormat(+new Date());
            $this.getEnrollDateList($this.rtId, $this.selectRsId, nowDateStr).then(res => {
              if ($this.selectTime != '') {
                $this.getCoachList($this.rtId, $this.selectRsId, $this.localDate, $this.selectTime);
              } else {
                $this.coachList = [];
              }
            })
          }
          $this.wechatShare();
        }, function () {
          $this.$loading.hide();
        }
      );
    },
    goToSectionDetail() { // 跳转至场次详情
      this.$routerGo(this, "push", {
        path: "/activity/activityDetail",
        query: { ActivityNo: this.rtId, from: 'sectionInfo', rsId: this.selectRsId, rpId: this.rpId, reId: this.reId, selectCityIndex: this.selectCityIndex }
      });
    },
    //分享
    wechatShare: function () {
      let title = this.dataInfo.sessionName;
      let shareImg = this.dataInfo.poster;
      let shareUrl = `${window.location.href.split("#")[0]}#/activity/activityDetail?ActivityNo=${this.rtId}&from=reservation&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = this.dataInfo.shareDesc || "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
    //手机端分享
    appShare: function () {
      utilJs.appShareTrue("", "", "", "");
    }
  },
  created() {
    utilJs.appShare(this);
  },
  activated() {
    setDocumentTitle("场次信息");// eslint-disable-line
    this.showHistoryDialog = false
    this.rtId = this.$route.query.rtId;
    // 改签过来的时候 会带reId rpId
    this.reId = this.$route.query.reId ? this.$route.query.reId : '';
    this.rpId = this.$route.query.rpId ? this.$route.query.rpId : '';
    this.periodsList = []
    this.historyList = []
    isLoadingHistory = false;
    this.weeked = '';
    this.localDate = '';
    this.selectIndex = 0;
    this.selectTimeIndex = 0;
    this.selectTime = '';
    this.myCalendarList = [];
    this.coachList = [];
    this.selectCoachIndex = 0;
    this.getSectionCityList()
  },
}
</script>
<style scoped>
.section-icon {
  -moz-box-shadow: -6px 1px 10px #fff;
  -webkit-box-shadow: -6px 1px 10px #fff;
  box-shadow: -6px 1px 10px #fff;
  position: absolute;
  right: 0;
  z-index: 10;
  background-color: #fff;
}
.history-box {
  box-shadow: 0px 0px 8px 1px rgba(35, 24, 21, 0.1);
}
</style>

